import { Game } from "../Game";
import GameConfig from "./GameConfig";
import { SquareGroup } from "../SquareGroup";
import { GameStatus, GameViewer } from "../types";
import PageConfig from "./PageConfig";
import { SquarePageViewer } from "./SquarePageViewer";
import $ from "jquery";

export class GamePageViewer implements GameViewer {
  private nextDom = $("#next");
  private panelDom = $("#panel");
  private showScoreDom = $("#score");
  private markDom = $("#mark");
  private gameDom = $("#mark p");

  init(game: Game): void {
    // 设置游戏面板
    this.panelDom.css({
      width: GameConfig.panelSize.width * PageConfig.squareSize.width,
      height: GameConfig.panelSize.height * PageConfig.squareSize.heigth
    });
    this.nextDom.css({
      width: GameConfig.nextSize.width * PageConfig.squareSize.width,
      height: GameConfig.nextSize.height * PageConfig.squareSize.heigth
    });

    this.showScore(game.score);

    // 事件监听
    $("html").on("keyup", e => {
      if (e.keyCode === 37) {
        game.controlLeft();
      } else if (e.keyCode === 38) {
        game.controlRotate();
      } else if (e.keyCode === 39) {
        game.controlRight();
      } else if (e.keyCode === 40) {
        game.controlDown();
      } else if (e.keyCode === 32) {
        if (game.gameStatus === GameStatus.playing) {
          game.pause();
        } else {
          game.start();
        }
      }
    });
  }

  onPause(): void {
    this.markDom.css({
      display: "flex"
    });
    this.gameDom.html("游戏暂停");
  }

  onStart(): void {
    // game.start(game.gameStatus === GameStatus.over);
    this.markDom.css({
      display: "none"
    });
    this.gameDom.html("");
  }

  onOver(): void {
    this.markDom.css({
      display: "flex"
    });
    this.gameDom.html("游戏结束");
  }

  showScore(score: number): void {
    this.showScoreDom.html(`${score.toString()} 分`);
  }

  showNext(teris: SquareGroup): void {
    teris.squares.forEach(sq => {
      sq.viewer = new SquarePageViewer(sq, this.nextDom);
    });
  }
  switch(teris: SquareGroup): void {
    teris.squares.forEach(sq => {
      sq.viewer!.remove();
      sq.viewer = new SquarePageViewer(sq, this.panelDom);
    });
  }
}
